package cn.jbolt.ndemo;

import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.provider.CommonNodeProvider;
import cn.jbolt.util.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jboltai.capability.text.JBoltText;
import com.jboltai.event.text.TextExtractEvent;
import org.springframework.stereotype.Component;

@Component
public class FileExtractorNode implements CommonNodeProvider {
    @Override
    public void provide(JsonNode nodeConfig, ChainContext context) {

        JsonNode data = context.getActionData().getData();
        String files = data.get("files").asText();
        ArrayNode jsonArray = JSONUtil.toJsonArray(files);
        ObjectNode node = JSONUtil.createObjectNode();
        for (JsonNode jsonNode : jsonArray) {
            String name = jsonNode.get("name").asText();
            String sn = jsonNode.get("sn").asText();
            String fileUrl = jsonNode.get("url").asText();
            TextExtractEvent event = JBoltText.extract(fileUrl).setStream(false).publish();
            event.await();
            if (event.isFail()) {
                context.sendErrorMsg("文档提取失败,失败原因:" + event.getError().getMsg());
                throw new RuntimeException(event.getError().getMsg(), event.getError().getException());
            }
            String content = event.getResult().getContent();//文档提取的内容

            if(sn.equals(DemoAppConstrant.PRODUCT_A)){
                node.put(DemoAppConstrant.PRODUCT_A, name);
                node.put(DemoAppConstrant.PRODUCT_A_DESC, content);
            }else{
                node.put(DemoAppConstrant.PRODUCT_B, name);
                node.put(DemoAppConstrant.PRODUCT_B_DESC, content);
            }
        }
        context.setAttr("prompt", JSONUtil.toJson(node));
    }
}
